<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>员工列表</title>
    <%--    <% pageContext.setAttribute("APP_PATH", request.getContextPath()); %>--%>

    <%--引入jquery--%>
    <script type="text/javascript" src="/js/jquery-3.3.1.js"></script>
    <%--引入bootstra样式--%>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <script src="/js/bootstrap.min.js"></script>



</head>
<body>

<!-- 员工添加 模态框 -->
<div class="modal fade" id="empAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">新增员工</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="empName_add_input" class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-10">
                            <input type="text" name="empName" class="form-control" id="empName_add_input" placeholder="姓名">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email_add_input" class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="text" name="email" class="form-control" id="email_add_input" placeholder="email">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender1_add_input" value="M" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender2_add_input" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email_add_input" class="col-sm-2 control-label">部门</label>
                        <div class="col-sm-4">
                            <select class="form-control" name="dId"></select>
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
            </div>
        </div>
    </div>
</div>



<!-- 员工修改 模态框 -->
<div class="modal fade" id="empUpdateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">员工修改</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="empName_add_input" class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-10">
                            <p class="form-control-static" id="empName_update_p"></p>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email_add_input" class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="text" name="email" class="form-control" id="email_update_input" placeholder="email">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender1_update_input" value="M" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender2_update_input" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email_add_input" class="col-sm-2 control-label">部门</label>
                        <div class="col-sm-4">
                            <select class="form-control" name="dId"></select>
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_update_btn">更新</button>
            </div>
        </div>
    </div>
</div>


<%--显示页面--%>
<div class="container">
    <%--标题--%>
    <div class="row">
        <div class="col-md-12">
            <h1>SSM-CRUD</h1>
        </div>
    </div>
    <%--按钮--%>
    <div class="row">
        <div class="col-md-4 col-md-offset-9">
            <button class="btn btn-primary" id="emp_add_modal_btn">新增</button>
            <button class="btn btn-danger" id="emp_delete_all_btn">删除</button>
        </div>
    </div>
    <%--数据--%>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover" id="emps_table">
                <thead>
                <tr>
                    <th><input type="checkbox" id="checkbox_all"/></th>
                    <th>序号</th>
                    <th>姓名</th>
                    <th>性别</th>
                    <th>email</th>
                    <th>部门</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                </tbody>

            </table>

        </div>
    </div>
    <%--分页信息--%>
    <div class="row">
        <%--分页文字--%>
        <div class="col-md-6" id="page_info"></div>
        <%--分页条--%>
        <div class="col-md-6" id="page_nav"></div>

    </div>

</div>
<script type="text/javascript">

    /*定义最大页数*/
    var maxpage;
    /*定义当前页码*/
    var now_pageNum;
    /*定义新增员工是否能提交*/
    var canSave =true;

    $(function () {
        to_page(1);
    });

    /*显示页面，调用显示三个区域方法*/
    function to_page(pn) {
        $.post("/emps", {pn: pn}, function (result) {
            /*显示表格内容*/
            build_emps_table(result);
            /*显示分页条内容*/
            build_page_nav(result);
            /*显示分页信息*/
            build_page_info(result);
        });
    }

    /*显示表格内容*/
    function build_emps_table(result) {
        $("#emps_table tbody").empty();
        var emps = result.extend.info.list;
        $.each(emps, function (index, item) {
            var checkBoxTd =$("<td><input type='checkbox' class='check_item'/></td>")
            var empIdTd = $("<td></td>").append(item.empId);
            var empNameTd = $("<td></td>").append(item.empName);
            var genderTd = $("<td></td>").append(item.gender == 'M' ? '男' : '女');
            var emailTd = $("<td></td>").append(item.email);
            var dempNameTd = $("<td></td>").append(item.department.deptName);
            var editbtn = $("<button></button>").addClass("btn btn-primary btn-sm")
                                                .append("<span></span>").addClass("glyphicon glyphicon-trash edit_btn")
                                                .append("编辑");
            /*为编辑按钮带上员工ID*/
            editbtn.attr("edit_id",item.empId);

            var delbtn = $("<button></button>").addClass("btn btn-danger btn-sm")
                                               .append("<span></span>").addClass("glyphicon glyphicon-trash del_btn")
                                               .append("删除");
            /*为删除按钮带上员工ID*/
            delbtn.attr("del_id",item.empId);

            var btnTd =$("<td></td>").append(editbtn).append(" ").append(delbtn);

            $("<tr></tr>").append(checkBoxTd)
                          .append(empIdTd)
                          .append(empNameTd)
                          .append(genderTd)
                          .append(emailTd)
                          .append(dempNameTd)
                          .append(btnTd)
                          .appendTo("#emps_table tbody");


        })


    }

    /*分页条数据*/
    function build_page_nav(result) {
        $("#page_nav").empty();
        /*翻页全选按钮设置为false*/
        $("#checkbox_all").prop("checked",false);
        var ul=$("<ul></ul>").addClass("pagination")
        var firstPageLi =$("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
        var previousLi =$("<li></li>").append($("<a></a>").append("&laquo;"));
        if (result.extend.info.hasPreviousPage == false){
            firstPageLi.addClass("disabled");
            previousLi.addClass("disabled");
        }else {
            firstPageLi.click(function () {
                to_page(1);
            });
            previousLi.click(function () {
                to_page(result.extend.info.pageNum-1);
            });
        }


        var nextLi =$("<li></li>").append($("<a></a>").append("&raquo;"));
        var listPageLi =$("<li></li>").append($("<a></a>").append("末页").attr("href","#"));
        if (result.extend.info.hasNextPage == false){
            nextLi.addClass("disabled");
            listPageLi.addClass("disabled");
        }else {
            nextLi.click(function () {
                to_page(result.extend.info.pageNum+1);
            });
            listPageLi.click(function () {
                to_page(result.extend.info.pages);
            });

        }


        ul.append(firstPageLi).append(previousLi);
        $.each(result.extend.info.navigatepageNums,function (index,item) {
            var numLi =$("<li></li>").append($("<a></a>").append(item));
            if (result.extend.info.pageNum ==item){
                numLi.addClass("active");
            }
            numLi.click(function () {
                to_page(item);
            });
                ul.append(numLi);
        })
        ul.append(nextLi).append(listPageLi);
        var page_nav=$("<nav></nav>").append(ul).prop("aria-label","Page navigation");
        page_nav.appendTo("#page_nav");

    }
    /*分页信息*/
    function build_page_info(result) {
        $("#page_info").empty();
        $("#page_info").append("当前第"+result.extend.info.pageNum+"页，当共"+result.extend.info.pages+"页，总共"+result.extend.info.total+"条记录");
        maxpage=result.extend.info.pages;
        now_pageNum=result.extend.info.pageNum;
    }

    /*点击新增加按钮事件*/
    $("#emp_add_modal_btn").click(function () {
        /*新增时清除表单旧数据*/
        $("#empAddModal form")[0].reset();
        /*新增时清除表单旧提示样式*/
        $("#empAddModal form").find("*").removeClass("has-success has-error");
        /*新增时清除表单旧提示信息*/
        $("#empAddModal form").find(".help-block").text("");
        /*是否能保存按钮变量变回true*/
        canSave=true;
        getDepts("#empAddModal select");
        $("#empAddModal").modal({
            backdrop:"static"
        });
    });

    /*新增员工-获得部门*/
    function getDepts(element) {
        $.post("/depts",{},function (result) {
            $(element).empty();
            $.each(result.extend.depts,function (index,item) {
                var optionEle =$("<option></option>").append(item.deptName).attr("value",item.deptId);
                optionEle.appendTo(element);
            });

        });
    }
    /*定义新增员工-校验方法*/
    function check_add_form(){
        /*检验姓名*/
        /*拿到姓名*/
        var empName = $("#empName_add_input").val();
        /*姓名正则表达式*/
        var regName =/(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5}$)/;
        /*检验失败提示*/
        if(!regName.test(empName)){
            // $("#empName_add_input").parent().addClass("has-error");
            // $("#empName_add_input").next("span").text("姓名只能是2~5位中文或6~16位英文数字组合！");
            show_check_msg("#empName_add_input","error","姓名只能是2~5位中文或6~16位英文数字组合！");
            return false;
        }else {
            show_check_msg("#empName_add_input","success","");
            // $("#empName_add_input").parent().addClass("has-success");
        }
        /*检查邮箱*/
        /*拿到邮箱*/
        var email = $("#email_add_input").val();
        /*邮箱正则表达式*/
        var regEmail =/^([a-zA-Z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        /*检验失败提示*/
        if (!regEmail.test(email)){
            // $("#email_add_input").parent().addClass("has-error");
            // $("#email_add_input").next("span").text("邮箱格式有误，请检查！");
            show_check_msg("#email_add_input","error","邮箱格式有误，请检查！");
            return false;
        }else {
            show_check_msg("#email_add_input","success","");
            // $("#email_add_input").parent().addClass("has-success");
        }
        return true;
    }

    /*抽取检查方法*/
    function show_check_msg(element,status,msg){
        /*先清除检查提示信息*/
        $(element).parent().removeClass("has-error has-success");
        $(element).next("span").text("");

        if ("success" ==status){
            $(element).parent().addClass("has-success");
            $(element).next("span").text(msg);

        }
        if ("error" ==status){
            $(element).parent().addClass("has-error");
            $(element).next("span").text(msg);

        }

    }

    /*判断用户名是否重复*/
    $("#empAddModal").on("change","#empName_add_input",function () {
        var empName = $("#empName_add_input").val();
        $.post("/checkHasEmp",{empName:empName},function (result) {
            if(result.code == 100){
                show_check_msg("#empName_add_input","success",result.extend.msg);
                canSave =true;
            }else {
                show_check_msg("#empName_add_input","error",result.extend.msg);
                canSave =false;
            }

        });
    })




    /*新增员工-保存*/
    $("#emp_save_btn").click(function () {
        /*表单校验*/
        if(!check_add_form()){
             return false;
        }

        /*检查保存按钮是否能点击*/
        if(canSave == false ){
            return false;
        }

        $.post("/emp",$("#empAddModal form").serialize(),function (result) {
            /*判断状态码*/
            if (result.code ==100){
                /*状态码成功*/
                /*关闭模态框*/
                $("#empAddModal").modal("hide");
                /*直接跳转到最后一页*/
                to_page(maxpage+1);
            }else {
                /*状态码失败*/

                if(undefined != result.extend.map.email){
                    show_check_msg("#email_add_input","error",result.extend.map.email);
                }

                if(undefined != result.extend.map.empName){
                    show_check_msg("#empName_add_input","error",result.extend.map.empName);
                }
            }


        });


    });


    /*员工编码按钮*/
    $(document).on("click",".edit_btn",function () {

        /*先查询部门信息*/
        getDepts("#empUpdateModal select");
        /*查询完员信息*/
        getEmp($(this).attr("edit_id"));
        /*把员工ID传到更新按钮上*/
        $("#emp_update_btn").attr("update_id",$(this).attr("edit_id"));
        /*打开模态框*/
        $("#empUpdateModal").modal({
            backdrop:"static"
        });
    });

    /*根据id获取员工信息写入编辑模态框*/
    function getEmp(id) {
        $.get("/emp/"+id,{},function (result) {
            $("#empName_update_p").text(result.extend.emp.empName);
            $("#email_update_input").val(result.extend.emp.email);
            $("#empUpdateModal input[name=gender]").val([result.extend.emp.gender]);
            $("#empUpdateModal select").val([result.extend.emp.dId]);
        });
    }

    /*编辑员工--更新按钮*/
    // $(document).on("click","#emp_update_btn",function () {
    // });
    $("#emp_update_btn").click(function () {

        /*检验邮箱*/
        var email = $("#email_update_input").val();
        /*邮箱正则表达式*/
        var regEmail =/^([a-zA-Z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        /*检验失败提示*/
        if (!regEmail.test(email)){

            show_check_msg("#email_update_input","error","邮箱格式有误，请检查！");
            return false;
        }else {
            show_check_msg("#email_update_input","success","");
        }

        /*邮箱检验完成后，执行更新操作*/
        $.ajax({
            url:"/emp/"+$(this).attr("update_id"),
            type:"PUT",
            data:$("#empUpdateModal form").serialize(),
            success:function (result) {
                /*关闭模态框*/
                $("#empUpdateModal").modal("hide");
                /*回到当前面*/
                to_page(now_pageNum);
            }

        });

    });

    /*点击列表删除按钮*/
    $(document).on("click",".del_btn",function () {
        var del_name=$(this).parents("tr").find("td:eq(2)").text();
        var del_id=$(this).attr("del_id");
        if (confirm("确认要删除【"+del_name+"】吗？")){
            $.ajax({
                url:"/emp/"+del_id,
                type:"DELETE",
                success:function (result) {
                    alert(result.msg);
                    /*回到当前页*/
                    to_page(now_pageNum);
                }

            });
        }
    });

    /*全选全不选*/
    $("#checkbox_all").click(function () {
        var checkbox_all_value = $(this).prop("checked");
        $(".check_item").prop("checked",checkbox_all_value);
    });

    /*列表单选*/
    $(document).on("click",".check_item",function () {
        var flag = $(".check_item:checked").length==$(".check_item").length;
        $("#checkbox_all").prop("checked",flag);

    });

    /*批量删除按钮*/
    $("#emp_delete_all_btn").click(function () {

        /*先判断是否有勾选内容*/
        if ($(".check_item:checked").length>0){
            /*定义删除时提示的名字字符串*/
            var del_empNames="";
            /*定义删除时id的字符串*/
            var del_empIds="";

            /*遍历选中的复制框,取出所有名字*/
            $.each($(".check_item:checked"),function () {
                del_empNames += $(this).parents("tr").find("td:eq(2)").text()+"，";
                del_empIds += $(this).parents("tr").find("td:eq(1)").text()+"-";
            })
            /*去除多少逗号（，）*/
            var del_empName= del_empNames.substring(0,del_empNames.length-1);
            /*去除多少横杠（-）*/
            var del_empIds= del_empIds.substring(0,del_empNames.length-1);

            /*批量删除，发送ajax请求*/
            if (confirm("确认要删除【"+del_empName+"】吗？")){
                $.ajax({
                    url:"/emp/"+del_empIds,
                    type:"DELETE",
                    success:function (result) {
                        alert(result.msg);
                        to_page(now_pageNum);
                    }
                });

            }
        }else {
            alert("请勾选后再尝试！");
        }



    });


</script>


</body>
</html>
